package com.zk.algorithm.array;

import com.zk.algorithm.annotation.Easy;
import com.zk.algorithm.annotation.Finished;
import com.zk.algorithm.annotation.LeetCodeExplore;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
 * Output: [4,9]
 *
 * 结果顺序不重要，都可以
 *
 * @author zk
 */
@Easy
@LeetCodeExplore
@Finished(false)
public class IntersectionOfTwoArrays2 {

    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);

        int start1 = 0;
        int start2 = 0;
        List<Integer> ans = new ArrayList<>();

        while (start1 < nums1.length && start2 < nums2.length) {
            if (nums1[start1] < nums2[start2]) {
                start1++;
            } else if (nums1[start1] > nums2[start2]) {
                start2++;
            } else {
                ans.add(nums1[start1]);
                start1++;
                start2++;
            }
        }

        int[] res = new int[ans.size()];
        int count = 0;
        for (int i : ans) {
            res[count++] = i;
        }

        return res;
    }

}
